/*
 * This code implements the MD5 message-digest algorithm(RFC1321), 
 * which is due to Ron Rivest. This code was written by Colin Plumb
 * in 1993, no copyright is claimed. This code is in the public domain;
 * do with it what you wish.
 * Equivalent code is available from RSA Data Security, Inc.
 * This code has been tested against that, and is equivalent,
 * except that you don't need to include two pages of legalese
 * with every copy.
 * To compute the message digest of a chunk of bytes, declare an
 * MD5Context structure, pass it to MD5Init, call MD5Update as
 * needed on buffers full of bytes, and then call MD5Final, which
 * will fill a supplied 16-byte array with the digest.
 */

#include "md5.h"
#include <string.h>
#include <endian.h>

/* This Algorithm treats byte array as litte endian order integer(32bit).
 * If os/cpu architecture is big endian, transform it.
 */
// transform each 4-byte(little endian) into int(32bit), ilen is length of int
static inline const uint32_t* byte_to_int(
	uint32_t *buf, const uint8_t *src, uint32_t ilen)
{
	#if __BYTE_ORDER == __BIG_ENDIAN
	const uint32_t *ret = buf;
	for(; ilen--; ++buf, src+=4) {
		*buf = (uint32_t) src[0] | src[1]<<8 | src[2]<<16 | src[3]<<24;
	}
	return ret;
	#else
	return (const uint32_t*)src;
	#endif
}
// transform each int(32bit) into 4-byte(little endian), ilen is length of int
static inline void int_to_byte(uint8_t *dest, const uint32_t *src, uint32_t ilen)
{
	#if __BYTE_ORDER == __BIG_ENDIAN
	uint32_t *idest = (uint32_t*)dest;
	const uint8_t *bsrc = (const uint8_t*)src;
	for(; ilen--; ++idest, bsrc+=4) {
		*idest = (uint32_t) bsrc[0] | bsrc[1]<<8 | bsrc[2]<<16 | bsrc[3]<<24;
	}
	#else
	if (dest!=(uint8_t*)src) memcpy(dest, src, (ilen)<<2);
	#endif
}


/*
 * The core of the MD5 algorithm, this alters an existing digest to
 * reflect the addition of 16 4-byte(32bit) of new data. MD5Update
 * blocks the data and converts bytes into digest for this routine.
 */
static void MD5Transform(struct MD5Context *ctx, const uint8_t data[64])
{
	uint32_t *D = ctx->digest;
	register uint32_t a=D[0], b=D[1], c=D[2], d=D[3];
	// transform 4-byte into int(32bit)
	const uint32_t *buf = byte_to_int((uint32_t *)ctx->buffer, data, 16);

// The four core functions - F1 is a little bit optimized
// (as found in Colin Plumbs public domain implementation)
// #define F1(x, y, z) ((x & y) | (~x & z))
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))

// recycle rotate 4-byte(32bit)
#define ROL(x, n)  ( ((x)<<(n)) | ((x)>>(32-(n))) )

// This is the central step in the MD5 algorithm. 
#define MD5STEP(f, a, b, c, d, data, s) \
	(a = ROL(a + f(b, c, d) + data, s) + b)

	MD5STEP(F1, a, b, c, d, buf[0] + 0xd76aa478, 7);
	MD5STEP(F1, d, a, b, c, buf[1] + 0xe8c7b756, 12);
	MD5STEP(F1, c, d, a, b, buf[2] + 0x242070db, 17);
	MD5STEP(F1, b, c, d, a, buf[3] + 0xc1bdceee, 22);
	MD5STEP(F1, a, b, c, d, buf[4] + 0xf57c0faf, 7);
	MD5STEP(F1, d, a, b, c, buf[5] + 0x4787c62a, 12);
	MD5STEP(F1, c, d, a, b, buf[6] + 0xa8304613, 17);
	MD5STEP(F1, b, c, d, a, buf[7] + 0xfd469501, 22);
	MD5STEP(F1, a, b, c, d, buf[8] + 0x698098d8, 7);
	MD5STEP(F1, d, a, b, c, buf[9] + 0x8b44f7af, 12);
	MD5STEP(F1, c, d, a, b, buf[10] + 0xffff5bb1, 17);
	MD5STEP(F1, b, c, d, a, buf[11] + 0x895cd7be, 22);
	MD5STEP(F1, a, b, c, d, buf[12] + 0x6b901122, 7);
	MD5STEP(F1, d, a, b, c, buf[13] + 0xfd987193, 12);
	MD5STEP(F1, c, d, a, b, buf[14] + 0xa679438e, 17);
	MD5STEP(F1, b, c, d, a, buf[15] + 0x49b40821, 22);

	MD5STEP(F2, a, b, c, d, buf[1] + 0xf61e2562, 5);
	MD5STEP(F2, d, a, b, c, buf[6] + 0xc040b340, 9);
	MD5STEP(F2, c, d, a, b, buf[11] + 0x265e5a51, 14);
	MD5STEP(F2, b, c, d, a, buf[0] + 0xe9b6c7aa, 20);
	MD5STEP(F2, a, b, c, d, buf[5] + 0xd62f105d, 5);
	MD5STEP(F2, d, a, b, c, buf[10] + 0x02441453, 9);
	MD5STEP(F2, c, d, a, b, buf[15] + 0xd8a1e681, 14);
	MD5STEP(F2, b, c, d, a, buf[4] + 0xe7d3fbc8, 20);
	MD5STEP(F2, a, b, c, d, buf[9] + 0x21e1cde6, 5);
	MD5STEP(F2, d, a, b, c, buf[14] + 0xc33707d6, 9);
	MD5STEP(F2, c, d, a, b, buf[3] + 0xf4d50d87, 14);
	MD5STEP(F2, b, c, d, a, buf[8] + 0x455a14ed, 20);
	MD5STEP(F2, a, b, c, d, buf[13] + 0xa9e3e905, 5);
	MD5STEP(F2, d, a, b, c, buf[2] + 0xfcefa3f8, 9);
	MD5STEP(F2, c, d, a, b, buf[7] + 0x676f02d9, 14);
	MD5STEP(F2, b, c, d, a, buf[12] + 0x8d2a4c8a, 20);

	MD5STEP(F3, a, b, c, d, buf[5] + 0xfffa3942, 4);
	MD5STEP(F3, d, a, b, c, buf[8] + 0x8771f681, 11);
	MD5STEP(F3, c, d, a, b, buf[11] + 0x6d9d6122, 16);
	MD5STEP(F3, b, c, d, a, buf[14] + 0xfde5380c, 23);
	MD5STEP(F3, a, b, c, d, buf[1] + 0xa4beea44, 4);
	MD5STEP(F3, d, a, b, c, buf[4] + 0x4bdecfa9, 11);
	MD5STEP(F3, c, d, a, b, buf[7] + 0xf6bb4b60, 16);
	MD5STEP(F3, b, c, d, a, buf[10] + 0xbebfbc70, 23);
	MD5STEP(F3, a, b, c, d, buf[13] + 0x289b7ec6, 4);
	MD5STEP(F3, d, a, b, c, buf[0] + 0xeaa127fa, 11);
	MD5STEP(F3, c, d, a, b, buf[3] + 0xd4ef3085, 16);
	MD5STEP(F3, b, c, d, a, buf[6] + 0x04881d05, 23);
	MD5STEP(F3, a, b, c, d, buf[9] + 0xd9d4d039, 4);
	MD5STEP(F3, d, a, b, c, buf[12] + 0xe6db99e5, 11);
	MD5STEP(F3, c, d, a, b, buf[15] + 0x1fa27cf8, 16);
	MD5STEP(F3, b, c, d, a, buf[2] + 0xc4ac5665, 23);

	MD5STEP(F4, a, b, c, d, buf[0] + 0xf4292244, 6);
	MD5STEP(F4, d, a, b, c, buf[7] + 0x432aff97, 10);
	MD5STEP(F4, c, d, a, b, buf[14] + 0xab9423a7, 15);
	MD5STEP(F4, b, c, d, a, buf[5] + 0xfc93a039, 21);
	MD5STEP(F4, a, b, c, d, buf[12] + 0x655b59c3, 6);
	MD5STEP(F4, d, a, b, c, buf[3] + 0x8f0ccc92, 10);
	MD5STEP(F4, c, d, a, b, buf[10] + 0xffeff47d, 15);
	MD5STEP(F4, b, c, d, a, buf[1] + 0x85845dd1, 21);
	MD5STEP(F4, a, b, c, d, buf[8] + 0x6fa87e4f, 6);
	MD5STEP(F4, d, a, b, c, buf[15] + 0xfe2ce6e0, 10);
	MD5STEP(F4, c, d, a, b, buf[6] + 0xa3014314, 15);
	MD5STEP(F4, b, c, d, a, buf[13] + 0x4e0811a1, 21);
	MD5STEP(F4, a, b, c, d, buf[4] + 0xf7537e82, 6);
	MD5STEP(F4, d, a, b, c, buf[11] + 0xbd3af235, 10);
	MD5STEP(F4, c, d, a, b, buf[2] + 0x2ad7d2bb, 15);
	MD5STEP(F4, b, c, d, a, buf[9] + 0xeb86d391, 21);

	D[0]+=a, D[1]+=b, D[2]+=c, D[3]+=d;
}

/*
 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
 * initialization constants.
 */
void MD5Init(struct MD5Context *ctx)
{
	ctx->digest[0] = 0x67452301;
	ctx->digest[1] = 0xefcdab89;
	ctx->digest[2] = 0x98badcfe;
	ctx->digest[3] = 0x10325476;
	ctx->low = ctx->high = 0;
}

/*
 * Update MD5Context with input data, length is at byte measure.
 */
void MD5Update(struct MD5Context *ctx, const void *data, unsigned int len)
{
	// update bit count
	uint32_t low = ctx->low;
	ctx->low += len<<3;
	if (ctx->low<low) ctx->high++;	// carry from low to high
	ctx->high += len>>29;
	// handle any leading odd-sized chunks
	const uint8_t *buf = (const uint8_t*)data;
	uint32_t offset = (low>>3) & 63;
	if (offset) {
		if (len<64-offset) {
			memcpy(ctx->buffer+offset, buf, len);
			return;
		}
		memcpy(ctx->buffer+offset, buf, 64-offset);
		buf += 64-offset;
		len -= 64-offset;
		MD5Transform(ctx, ctx->buffer);
	}
	// process data in 64-byte chunks
	for(; len>63; len-=64, buf+=64) {
		MD5Transform(ctx, buf);
	}
	// handle any remaining bytes of data. 
	memcpy(ctx->buffer, buf, len);
}

/*
 * Final wrapup - Append Boundary(1-byte: 0x80) to end, and append 
 * Bitcount(8-byte: low, high). There are several zero bytes between
 * Boundary and Bitcount, which make sure each chunk is 64-byte, and 
 * Bitcount must be the last 8-byte in chunk.
 */
void MD5Final(unsigned char digest[16], struct MD5Context *ctx)
{
	uint32_t offset = (ctx->low>>3) & 63;
	ctx->buffer[offset++] = 0x80;
	// current chunk no more space to store last Bitcount,
	// fill last space as zero, and digest this chunk.
	if (offset>56) {
		memset(ctx->buffer+offset, 0, 64-offset);
		offset = 0;
		MD5Transform(ctx, ctx->buffer);
	}
	// fill first padding 56-byte, copy Bitcount to last 8-byte
	memset(ctx->buffer+offset, 0, 56-offset);
	int_to_byte(ctx->buffer+56, &ctx->low, 1);
	int_to_byte(ctx->buffer+60, &ctx->high, 1);
	MD5Transform(ctx, ctx->buffer);
	// message digest result
	int_to_byte(digest, ctx->digest, 4);
	// clear sensitive message
	memset(ctx, 0, sizeof(struct MD5Context));
}

/*
 * Transform 16 bytes digest into 32 bytes Hex String.
 */
void MD5HexString(char hex[33], const unsigned char digest[16])
{
	static const char HEX[] = "0123456789abcdef";
	int i = 0;
	for(; i<16; ++i) {
		hex[i*2+0] = HEX[(digest[i]>>4)&0xF];
		hex[i*2+1] = HEX[(digest[i]>>0)&0xF];
	}
	hex[32] = '\0';
}
